// Created by carolsail

import { StaticInstance } from './StaticInstance';
import { ENUM_RESOURCE_TYPE, ENUM_UI_TYPE } from './Enum';
import AudioManager from "./manager/AudioManager";
import DataManager from './manager/DataManager';
import ResourceManager from "./manager/ResourceManager";
import SdkManager from './manager/SdkManager';
import { WsClient } from 'tsrpc-browser';
import { serviceProto } from './shared/protocols/serviceProto';
import ToastManager from './manager/ToastManager';
const { ccclass, property } = cc._decorator;

@ccclass
export default class Index extends cc.Component {

    onLoad() {
        this.node.getChildByName('UI').opacity = 255
        cc.view.setResizeCallback(() => this.responsive())
        this.responsive()
        // DataManager.instance.loadingRate = 0
        // // 联机
        // DataManager.instance.wsClient = new WsClient(serviceProto, {
        //     server: 'ws://127.0.0.1:3006',
        //     // server: 'ws://192.168.1.192:3006',
        //     // server: 'wss://一级域名:3005',
        // })
        // this.connect()
        // DataManager.instance.wsClient.flows.postDisconnectFlow.push((v: any) => {
        //     setTimeout(() => { this.connect() }, 2000)
        //     return v
        // })
    }

    async start() {
        // 加载资源
        for (const index in ENUM_RESOURCE_TYPE) {
            const resource = ENUM_RESOURCE_TYPE[index]
            await ResourceManager.instance.loadRes(resource)
        }
        // console.log(ResourceManager.instance.spritesMap)
        // 加载ui
        StaticInstance.uiManager.init()
        // 读档
        DataManager.instance.restore()
        // 播放音乐
        AudioManager.instance.playMusic()
        // 加载sdk
        SdkManager.instance.initAudioEndListener()
        SdkManager.instance.passiveShare()
        SdkManager.instance.getRank()
        SdkManager.instance.initBannerAd()
        SdkManager.instance.initInterstitialAd()
        SdkManager.instance.initVideoAd()
        // 操作ui
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, true, () => {
            DataManager.instance.loadingRate = 1
            this.checkShared()
        })
    }

    // 屏幕响应式
    responsive() {
        const designSize = cc.view.getDesignResolutionSize();
        const viewSize = cc.view.getFrameSize();

        const setFitWidth = () => {
            cc.Canvas.instance.fitHeight = false;
            cc.Canvas.instance.fitWidth = true;
        }

        const setFitHeight = () => {
            cc.Canvas.instance.fitHeight = true;
            cc.Canvas.instance.fitWidth = false;
        }

        const setFitBoth = () => {
            cc.Canvas.instance.fitHeight = true;
            cc.Canvas.instance.fitWidth = true;
        }

        const designRatio = designSize.width / designSize.height
        const viewRatio = viewSize.width / viewSize.height
        if (designRatio < 1) {
            if (viewRatio < 1) {
                if (viewRatio > designRatio) {
                    setFitBoth()
                } else {
                    setFitWidth()
                }
            } else {
                setFitBoth()
            }
        } else {
            if (viewRatio > 1) {
                if (viewRatio < designRatio) {
                    setFitBoth()
                } else {
                    setFitHeight()
                }
            } else {
                setFitBoth()
            }
        }
    }

    async connect(): Promise<void> {
        let res = await DataManager.instance.wsClient.connect();
        if (!res.isSucc) {
            await new Promise(rs => { setTimeout(rs, 2000) });
            await this.connect();
        }
    }

    // 检查被邀请
    checkShared() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            const roomId = SdkManager.instance.getShareQuery('roomId')
            if (roomId) {
                const shareTime = SdkManager.instance.getShareQuery('shareTime')
                if (!DataManager.instance.lastSharedTime || shareTime > DataManager.instance.lastSharedTime) {
                    this.joinRoom(roomId, shareTime)
                } else {
                    ToastManager.instance.show('邀请已失效', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
                }
            }
            window['wx'].onShow((res: any) => {
                const roomId = res['query']['roomId']
                if (roomId) {
                    const shareTime = res['query']['shareTime']
                    if (!DataManager.instance.lastSharedTime || shareTime > DataManager.instance.lastSharedTime) {
                        this.joinRoom(roomId, shareTime)
                    } else {
                        ToastManager.instance.show('邀请已失效', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
                    }
                }
            })
        }
    }

    // 根据分享参数入房间
    async joinRoom(roomId: string, shareTime: number) {
        // console.log(roomId, shareTime)
        if (StaticInstance.uiManager.isActive(ENUM_UI_TYPE.MENU)
            || StaticInstance.uiManager.isActive(ENUM_UI_TYPE.HALL)
            || StaticInstance.uiManager.isActive(ENUM_UI_TYPE.ROOM_CREATE)
            || StaticInstance.uiManager.isActive(ENUM_UI_TYPE.ROOM_JOIN)
            || StaticInstance.uiManager.isActive(ENUM_UI_TYPE.ROOM_JOIN_NUM)
            || StaticInstance.uiManager.isActive(ENUM_UI_TYPE.MORE)
            || StaticInstance.uiManager.isActive(ENUM_UI_TYPE.SKIN)
        ) {
            DataManager.instance.shareRoomId = roomId
            DataManager.instance.lastSharedTime = shareTime
            DataManager.instance.save()
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.SHARE)
        } else {
            ToastManager.instance.show('对战中，未能接受邀请', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
        }
    }
}
